package com.peach.stock.service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.peach.stock.domain.Stock12Model;
import com.peach.stock.domain.Stock11Model;
import com.peach.stock.mapper.StockMapper;

/**
 * 数据获取接口
 * @author lfzhou
 *
 */
@Service
public class DataAPIService {

	private static final Logger log = LoggerFactory.getLogger(DataAPIService.class);
	
	@Autowired
	private RestTemplate restTemplate;
	
	@Autowired
	StockMapper mapper;
	
	
//	
	public void szse()
	{
		// 股票基本信息-上证主版A股
		String page = "1";
		String url = "http://query.sse.com.cn/security/stock/getStockListData2.do?"
				+ "&jsonCallBack=jsonpCallback42742&isPagination=true&stockCode=&csrcCode=&areaName="
				+ "&stockType=1&pageHelp.cacheSize=1&pageHelp.beginPage=%s&pageHelp.pageSize=25"
				+ "&pageHelp.pageNo=%s&pageHelp.endPage=%s1&_="+System.currentTimeMillis();
		String result = getData(String.format(url, page, page, page));
		String json = result.substring(result.indexOf("{"));
		Map map = json2map(json);
		Object data = map.get("data");
		Object count = map.get("pageCount");
		log.info(count.toString());
//		
		
//		//主板
//		String url = "http://www.szse.cn/api/report/ShowReport/data?SHOWTYPE=JSON&CATALOGID=1110&TABKEY=tab1&PAGENO=2&random=0.9015973912415391";
//		String json = getData(url);
//		log.info(json);
	}
	
	public void getHQ(String rq)
	{
		if (StringUtils.isEmpty(mapper.select21(rq)))
		{//新采集
			List<String> lst = mapper.select02By02();
			for (String hy : lst)
			{
				getHQByHy02From163(hy, rq);
			}
			
			String sh = getData("http://hq.sinajs.cn/list=s_sh000001");
			BigDecimal shzs = new BigDecimal(sh.split(",")[1].trim());
			String sz = getData("http://hq.sinajs.cn/list=s_sz399001");
			BigDecimal szzs = new BigDecimal(sz.split(",")[1].trim());
			mapper.insert21(rq, shzs, szzs);
		}
		else
		{
			log.info("已经采集:" + rq);
		}
		
	}
	
	/**
	 * http://quotes.money.163.com/old/#DC
	 * Financial Report
	 * 从163获取财报信息。沪深F10 > 公司财报 > 财报查询
	 * @param date 报告日期。一季度03-31\06-30\09-30\12-31
	 */
	public int getFRFrom163(String date)
	{
		//财报查询
		String url = "http://quotes.money.163.com/hs/marketdata/service/cwsd.php?"
				+ "host=/hs/marketdata/service/cwsd.php&page=%s&query=date:%s&fields=NO,"
				+ "SYMBOL,SNAME,PUBLISHDATE,MFRATIO28,MFRATIO18,MFRATIO20,MFRATIO10,MFRATIO4,"
				+ "MFRATIO2,MFRATIO12,MFRATIO23,MFRATIO25,MFRATIO24,MFRATIO122&sort=SYMBOL&order=asc&"
				+ "count=25&type=query&initData=[object%20Object]&callback=callback_998899825&req=62228";
		int page = 0;
		String result = getData(String.format(url, page, date));
		String json = result.substring(result.indexOf("{"), result.lastIndexOf("}") + 1);
		Map map = json2map(json);
		// 获取总页数
		int pagecount = Integer.parseInt(map.get("pagecount").toString());
		int i = createFR((List<Map>)map.get("list"), date);
		
		while (page < pagecount)
		{
			page++;
			log.info("page:{}", page);
			result = getData(String.format(url, page, date));
			json = result.substring(result.indexOf("{"), result.lastIndexOf("}") + 1);
			i = i + createFR((List<Map>)json2map(json).get("list"), date);
		}
		return i;
	}
	
	private int createFR(List<Map> data, String rq)
	{
		int i = 0;
		for (Map map : data )
		{
			Stock12Model stock12model = new Stock12Model();
			stock12model.setDm(map.get("SYMBOL").toString());
			stock12model.setRq(rq);
			stock12model.setMgsy(conv(map.get("MFRATIO28")));
			stock12model.setZysr(conv(map.get("MFRATIO10")));
			stock12model.setZylr(conv(map.get("MFRATIO4")));
			stock12model.setJlr(conv(map.get("MFRATIO2")));
			stock12model.setZzc(conv(map.get("MFRATIO12")));
			stock12model.setLdzc(conv(map.get("MFRATIO23")));
			stock12model.setZfz(conv(map.get("MFRATIO25")));
			stock12model.setLdfz(conv(map.get("MFRATIO24")));
			stock12model.setJzc(conv(map.get("MFRATIO122")));
			mapper.insert12(stock12model);
			i++;
		}
		return i;
	}
	
	/**
	 * http://quotes.money.163.com/old/#DC
	 * Financial Report
	 * 从163获取行情数据，按照hy02
	 * @param hy02 05表
	 */
	public int getHQByHy02From163(String hy02, String rq)
	{
		String url = "http://quotes.money.163.com/hs/service/diyrank.php?"
				+ "host=http://quotes.money.163.com/hs/service/diyrank.php&page=%s&"
				+ "query=PLATE_IDS:hy%s&fields=NO,SYMBOL,NAME,PRICE,PERCENT,UPDOWN,FIVE_MINUTE,"
				+ "OPEN,YESTCLOSE,HIGH,LOW,VOLUME,TURNOVER,HS,LB,WB,ZF,PE,MCAP,TCAP,MFSUM,"
				+ "MFRATIO.MFRATIO2,MFRATIO.MFRATIO10,SNAME,CODE,ANNOUNMT,UVSNEWS&sort=SYMBOL&order=asc&count=24&type=query";
		
		int page = 0;
//		String result = getData(url, page, hy02);
		String result = getData(String.format(url, page, hy02));
		
		Map map = json2map(result);
		// 获取总页数
		int pagecount = Integer.parseInt(map.get("pagecount").toString());
		int i = createHQ((List<Map>)map.get("list"), hy02, rq);
		
		while (page < pagecount)
		{
			page++;
			log.info("page:{}", page);
			result = getData(String.format(url, page, hy02));
			i = i + createHQ((List<Map>)json2map(result).get("list"), hy02, rq);
		}
		
		return i;
	}
	
	private String getData(String url, int page, String hy02)
	{
		
		String result = "";
		
		boolean b = true;
		while(b)
		{
			try {
				result = restTemplate.getForEntity(url, String.class, page, hy02).getBody();
				b = false;
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				try {
					Thread.sleep(3000);
				} catch (InterruptedException ee) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	
	private String getData(String url)
	{
        String result = "";
		boolean b = true;
		while(b)
		{
			try {
				result = restTemplate.getForEntity(url, String.class).getBody();
				b = false;
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				try {
					Thread.sleep(3000);
				} catch (InterruptedException ee) {
					log.error(e.getMessage(), e);
				}
			}
		}
		return result;
	}
	
	private int createHQ(List<Map> data, String hy02, String rq)
	{
		int i = 0;
		for (Map map : data )
		{
//			{CODE=1000592, FIVE_MINUTE=0, HIGH=3.28, HS=0.02140941979702, LB=1.6606952994071, LOW=3.19, MCAP=6.25991032782E9, 
//			MFRATIO={MFRATIO2=2386324.95, MFRATIO10=3.7727255935E8}, MFSUM=0.0081, NAME=平潭发展, OPEN=3.2, PE=403.7037037037, 
//			PERCENT=0.025078, PRICE=3.27, SNAME=平潭发展, SYMBOL=000592, TCAP=6.31692351684E9, TURNOVER=1.3260589474E8, UPDOWN=0.08, 
//			VOLUME=40985030, WB=-0.13339186910287, YESTCLOSE=3.19, ZF=0.028213166144201, NO=1}
			String zqdm = map.get("CODE").toString().trim();
//			log.info(zqdm);
			if (zqdm.length() == 7)
			{
				zqdm = zqdm.substring(1);
			}
			
			if (mapper.select01(zqdm) == null)
			{
				mapper.insert01(zqdm, (String)map.get("SNAME"), hy02);
				log.info("==== add:" + zqdm);
			}
			
//			if (!pch02Dao.existsById(id)) {
				Stock11Model stockModel = new Stock11Model();
//				stockModel.setDm(zqdm);
//				stockModel.setRq(rq);
//				stockModel.setPrice(conv(map.get("PRICE")));
//				stockModel.setPercent(conv(map.get("PERCENT")).multiply(new BigDecimal(100)));
//				stockModel.setUpdown(conv(map.get("UPDOWN")));
//				stockModel.setFiveminute(conv(map.get("FIVE_MINUTE")));
//				stockModel.setOpen(conv(map.get("OPEN")));
//				stockModel.setYestclose(conv(map.get("YESTCLOSE")));
//				stockModel.setHigh(conv(map.get("HIGH")));
//				stockModel.setLow(conv(map.get("LOW")));
//				stockModel.setVolume(conv(map.get("VOLUME")));
//				stockModel.setTurnover(conv(map.get("TURNOVER")));
//				BigDecimal hs = conv(map.get("HS"));
//				if (hs != null) 
//				{
//					stockModel.setHs(hs.multiply(new BigDecimal(100)));	
//				}
//				
//				stockModel.setLb(conv(map.get("LB")));
//				
//				BigDecimal wb = conv(map.get("WB"));
//				if (wb != null)
//				{
//					stockModel.setWb(wb.multiply(new BigDecimal(100)));	
//				}
//				BigDecimal zf = conv(map.get("ZF"));
//				if (zf != null)
//				{
//					stockModel.setZf(zf.multiply(new BigDecimal(100)));
//				}
//				
//				stockModel.setPe(conv(map.get("PE")));
//				stockModel.setMcap(conv(map.get("MCAP")));
//				stockModel.setTcap(conv(map.get("TCAP")));
//				stockModel.setMfsum(conv(map.get("MFSUM")));
//				
//				if (map.get("MFRATIO") != null)
//				{
//					Map mfratio = (Map)map.get("MFRATIO");
//					stockModel.setMfratio2(conv(mfratio.get("MFRATIO2")));
//					stockModel.setMfratio10(conv(mfratio.get("MFRATIO10")));
//				}
				
				mapper.insert11(stockModel);
				
//			}
			
			i++;
		}
		return i;
	}
//	
//	private void addStockModel(StockModel total, StockModel stockModel)
//	{
//		//====汇总
//		if (total.getVolume() == null)
//		{
//			total.setVolume(stockModel.getVolume()==null?new BigDecimal(0):stockModel.getVolume());
//		}
//		else
//		{
//			total.setVolume(total.getVolume().add(stockModel.getVolume()==null?new BigDecimal(0):stockModel.getVolume()));
//		}
//		
//		if (total.getTurnover() == null)
//		{
//			total.setTurnover(stockModel.getTurnover()==null?new BigDecimal(0):stockModel.getTurnover());
//		}
//		else
//		{
//			total.setTurnover(total.getTurnover().add(stockModel.getTurnover()==null?new BigDecimal(0):stockModel.getTurnover()));
//		}
//		
//		if (total.getMcap() == null)
//		{
//			
//			total.setMcap(stockModel.getMcap()==null?new BigDecimal(0):stockModel.getMcap());
//		}
//		else
//		{
//			total.setMcap(total.getMcap().add(stockModel.getMcap()==null?new BigDecimal(0):stockModel.getMcap()));
//		}
//		
//		if (total.getTcap() == null)
//		{
//			total.setTcap(stockModel.getTcap()==null?new BigDecimal(0):stockModel.getTcap());
//		}
//		else
//		{
//			total.setTcap(total.getTcap().add(stockModel.getTcap()==null?new BigDecimal(0):stockModel.getTcap()));
//		}
//	}
	
	private Map json2map(String json)
	{
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.readValue(json, Map.class);
		} catch (JsonProcessingException e) {
			log.error(e.getMessage(), e);
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	private BigDecimal conv(Object s)
	{
		if (StringUtils.isEmpty(s))
		{
			return null;
		}
		try {
			return new BigDecimal(s.toString().trim().replace(",", ""));
		} catch (NumberFormatException e) {
			log.error(s.toString());
			return null;
		}
		
		
	}
}
